import 'dart:developer';
import 'package:ball_lion/module/match/match_support_widget.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ball_lion/module/match/detail/lq_match_detail_logic.dart';
import 'package:ball_lion/entity/match/detail/lq_detail_head_entity.dart';
import 'package:ball_lion/entity/match/match_live_entity.dart';
import 'package:ball_lion/resources/colours.dart';
import 'package:ball_lion/resources/styles.dart';
import 'package:ball_lion/utils/date_time_utils.dart';
import 'package:ball_lion/routes/routes.dart';
import 'package:ball_lion/utils/toast_utils.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/utils/widget_utils.dart';
import 'package:ball_lion/module/match_detail/live/live_source_sheet.dart';
import 'package:url_launcher/url_launcher_string.dart';
import 'package:ball_lion/module/live/live_chat_logic.dart';
import 'package:ball_lion/widgets/player/qs_player_logic.dart';
import 'package:ball_lion/widgets/base/wqs_text.dart';
import 'package:ball_lion/widgets/circular.dart';
import 'package:ball_lion/widgets/gif.dart';

class LqDetailHeadWidget extends StatefulWidget {
  const LqDetailHeadWidget(
      {super.key, this.detail, this.id, required this.logic});

  final LqDetailHeadInfoEntity? detail;
  final int? id;
  final LqMatchDetailLogic logic;
  // final List<MatchVideoEntity>? videoList;

  @override
  State<LqDetailHeadWidget> createState() => _LqDetailHeadWidgetState();
}

class _LqDetailHeadWidgetState extends State<LqDetailHeadWidget> {
  LqDetailHeadInfoEntity? get detail => widget.detail;
  LqMatchDetailLogic get logic => widget.logic;

  @override
  Widget build(BuildContext context) {
    return DefaultTextStyle(
      style: const TextStyle(color: Colors.white),
      child: Container(
        padding: EdgeInsets.only(
            top: kToolbarHeight + MediaQuery.of(context).padding.top),
        decoration: BoxDecoration(
            image: DecorationImage(
                image: AssetImage(Utils.getImgPath('zq_detail_header.png')),
                fit: BoxFit.fitWidth)),
        child: Stack(
          children: [
            Row(
              children: [
                _team(detail?.awayTeamName ?? "", detail?.awayPosition ?? "",
                    detail?.awayTeamLogo ?? ""),
                _matchStatus(),
                _team(detail?.homeTeamName ?? "", detail?.homePosition ?? "",
                    detail?.homeTeamLogo ?? "",
                    isHome: true),
              ],
            ),
            Positioned(
                left: 0,
                right: 0,
                bottom: 0,
                child: SizedBox(
                  height: 22,
                  child: MatchSupportWidget(
                      detail?.guestInter ?? '0',
                      detail?.homeInter ?? '0',
                      detail?.guestInterCount ?? 0,
                      detail?.homeInterCount ?? 0,
                      detail?.isInter ?? false,
                      widget.id ?? 0,
                      detail?.awayTeamId ?? 0,
                      detail?.homeTeamId ?? 0),
                ))
          ],
        ),
      ),
    );
  }

  Widget _team(String name, String rank, String icon, {bool isHome = false}) {
    String n = isHome ? '主' : '客';
    if (rank.isNotEmpty) {
      n = '$n/$rank';
    }
    return Expanded(
      child: GestureDetector(
        onTap: () {
          final id = isHome ? detail?.homeTeamId : detail?.awayTeamId;
          Utils.onEvent('bsxq', params: {"bsxq": isHome ? 2 : 3});
          Get.toNamed(Routes.lqTeamDetail, arguments: id);
        },
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            icon.length == 0 && detail == null
                ? Styles.placeholderIcon(width: 52, height: 52)
                : CachedNetworkImage(
                    fit: BoxFit.contain,
                    imageUrl: icon,
                    placeholder: (context, url) => Styles.placeholderIcon(),
                    errorWidget: (context, url, error) => Image.asset(
                      Utils.getImgPath('lq_placeholder.png'),
                      width: 52,
                      height: 52,
                    ),
                  ).sized(width: 52, height: 52),
            const SizedBox(height: 10),
            QsText(
              name,
              fontWeight: FontWeight.w500,
              maxLines: 1,
              textAlign: TextAlign.center,
            ),
            QsText("[$n]",
                fontSize: 10,
                color: Colours.white.withOpacity(0.6),
                maxLines: 1)
          ],
        ),
      ),
    );
  }

  Widget _matchStatus() {
    if (detail?.statusId == 1 && detail?.matchDateTime != null) {
      return Column(children: [
        const SizedBox(height: 35),
        QsText(detail?.matchDateTime?.formatedString('MM-dd HH:mm') ?? "",
            fontSize: 22),
        const Spacer(),
        if (logic.roomList.hasValue) videoWidget(),
        const SizedBox(height: 16)
        // ],
      ]);
    }
    return Container(
      width: 162,
      padding: const EdgeInsets.only(bottom: 15),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          const SizedBox(height: 5),
          if (detail?.statusId == 10)
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Container(
                  width: 42,
                  height: 20,
                  decoration: BoxDecoration(
                      color: const Color(0x6EFDFDFD),
                      borderRadius: BorderRadius.circular(10)),
                  alignment: Alignment.center,
                  child: QsText("完场", fontSize: 12),
                ),
              ],
            ),
          if (detail?.statusId != 10)
            QsText((detail?.statusMap[detail?.statusId] ?? "") +
                (detail?.getRemainingTime ?? "")),
          QsText(
            "${detail?.awayScore ?? ""} - ${detail?.homeScore ?? ''}",
            fontSize: 22,
            fontWeight: FontWeight.w500,
            fontFamily: "Din",
          ),
          if (detail?.halfScore != null) QsText(detail?.halfScore ?? ''),
          if (detail?.matchPursueScore != null && detail?.matchScore != null)
            QsText("差 ${detail?.matchPursueScore}  总 ${detail?.matchScore}"),
          const Spacer(),
          if (logic.roomList.hasValue) videoWidget(),
          const SizedBox(height: 16)
        ].map((e) => e is Spacer ? e : e.marginOnly(bottom: 4)).toList(),
      ),
    );
  }

  Widget videoWidget() {
    bool hasVideo =
        logic.roomList?.any((element) => element.vtype != 4) ?? false;
    bool onLive = logic.roomList?.any(
            (element) => element.roomId != 0 && element.playStatus == 1) ??
        false;
    bool hasAnimation =
        logic.roomList?.any((element) => element.vtype == 4) ?? false;
    return Circular(
        radius: 10,
        color: Colours.black.withOpacity(0.15),
        height: 20,
        padding: const EdgeInsets.symmetric(horizontal: 8),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            if (hasVideo)
              GestureDetector(
                onTap: () => onTapLive(),
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    if (onLive)
                      const GifWidget(
                          width: 14,
                          height: 14,
                          asset: "in_live.gif",
                          duration: Duration(milliseconds: 500))
                    else
                      Image.asset(
                        Utils.getImgPath("live_video_border.png"),
                        width: 14,
                      ),
                    const SizedBox(width: 2),
                    const QsText("视频直播", fontSize: 12, color: Colours.white)
                  ],
                ),
              ),
            if (hasVideo && hasAnimation)
              const QsText(" | ", fontSize: 12, color: Colours.white),
            if (hasAnimation)
              GestureDetector(
                onTap: () => onTapLive(false),
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Image.asset(
                      Utils.getImgPath("live_animation_border.png"),
                      width: 14,
                    ),
                    const SizedBox(width: 2),
                    const QsText("动画直播", fontSize: 12, color: Colours.white)
                  ],
                ),
              )
          ],
        ));
  }

  onTapLive([bool isLive = true]) async {
    Utils.onEvent('bsxq_dhzb');
    if (logic.roomList.noValue) {
      await logic.getVideo();
    }
    if (logic.roomList.hasValue) {
      int? index;
      if (isLive) {
        index = await LiveSourceSheet.show(
            liveList: logic.roomList
                    ?.where((element) => element.vtype != 4)
                    .toList() ??
                [],
            select: logic.liveInfo?.expertId);
      } else {
        index = logic.roomList?.indexWhere((element) => element.vtype == 4);
      }
      if (index != null) {
        MatchLiveEntity live = logic.roomList![index];
        if (isLive && !live.playStatus.hasValue) {
          Toast.text("暂未开始直播，请耐心等待");
          return;
        }
        if (live.vformat == 'URL') {
          launchUrlString(live.url ?? '',
              mode: LaunchMode.externalApplication,
              webViewConfiguration:
                  const WebViewConfiguration(enableDomStorage: false));
        } else {
          if (live.copyright == 0) {
            logic.setLiveStream(true, roomInfo: live);
            try {
              LiveChatLogic chatLogic =
                  Get.find<LiveChatLogic>(tag: "${live.matchId}");
              chatLogic.getRefresh();
            } catch (e) {
              log("");
            }
            try {
              QsPlayerLogic playerLogic =
                  Get.find<QsPlayerLogic>(tag: "${live.matchId}");
              playerLogic.url = live.url ?? "";
              playerLogic.doRefresh();
            } catch (e) {
              log("");
            }
          } else {
            Toast.text('暂无版权，请选择其他直播源');
          }
        }
      }
    }
  }
}
